<template>
  <view class="container">
    <view class="upload">
      <button @click="handleFileChange">上传图片</button>
      <input type="file" @change="handleFileChange" style="display: none" ref="fileInput" />
    </view>
    <view class="result" v-if="result">
      <text>识别结果：{{ result }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      result: null,
      filePath: '',
    };
  },
  methods: {
    handleFileChange(event) {
      this.postImageToBaidu();
      return
      const file = event.target.files[0];
      if (!file) {
        return;
      }
      this.filePath = file;
      this.cropperImage(file);
    },
    cropperImage(file) {
      // 这里可以添加图片裁剪逻辑，如果需要
      // ...
      // 假设裁剪成功后，我们将文件转换为Base64
      const reader = new FileReader();
      reader.onload = (e) => {
        const base64 = e.target.result;
        this.postImageToBaidu(base64);
      };
      reader.readAsDataURL(file);
    },
    postImageToBaidu(base64Image) {
      const url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/animal';
      const params = {
        url: 'https://i2.3conline.com/images/piclib/201203/22/batch/1/130539/1332349654033obqessjgay.jpg',
        baike_num: '10',
        top_num: '10',
        'access_token': '24.ba393f17a3ce2693345aedc4111c17d1.2592000.1722239336.282335-35389279'
      };

      const header = {
        'Content-Type': 'application/x-www-form-urlencoded',
      };

      uni.request({
        url: url,
        method: 'POST',
        data: params,
        header: header,
        success: (res) => {
          console.log(11111111, res);
          if (res.data && res.data.result) {
            this.result = res.data.result;
          } else {
            this.result = '无法识别';
          }
        },
        fail: () => {
          this.result = '请求失败';
        }
      });
    },
    encodeParams(params) {
      return Object.keys(params).map((key) => {
        return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
      }).join('&');
    },
    uploadImage() {
      // const fileInput = this.$refs.fileInput;
      // fileInput.click();
    }
  }
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.upload {
  margin-bottom: 20px;
}
.result text {
  color: #333;
}
</style>
